package com.fengxu.netty.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.URI;

// httpServerHandler的处理器用来处理http的对象属性
// SimpleChannelInboundHandler继承自ChannelInboundHandlerAdapter
// HttpObject对象时客户端和服务器端交互信息的封装
public class HttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        if(msg instanceof HttpRequest){
            System.out.println("msg 的类型: "+msg.getClass());
            System.out.println("客户端的地址是: "+ ctx.channel().remoteAddress());
            HttpRequest httpRequest = (HttpRequest) msg;

            // 过滤请求
            if(new URI(httpRequest.uri()).getPath().equals("/favicon.ico")){
                System.out.println("服务器接收到了请求但不做相应");
                return;
            }

            // 回复信息给浏览器
            ByteBuf byteBuf = Unpooled.copiedBuffer("hello 客户端", CharsetUtil.UTF_8);
            DefaultFullHttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, byteBuf);
            // 设置http头
            httpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain;charset=UTF-8")
                    .set(HttpHeaderNames.CONTENT_LENGTH,byteBuf.readableBytes());
            // 发出信息
            ctx.writeAndFlush(httpResponse);
        }
    }
}
